// Definition of the Socket class

#ifndef Socket_class
#define Socket_class


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <arpa/inet.h>
#include "common.h"
#include "NetPacket.h"


const int MAXHOSTNAME = 200;
const int MAXCONNECTIONS = 5;
const int MAXRECV = 1024 * 1024;



class IObserver
{
public:
    virtual void RevData(const int fd, const unsigned short& nOpcode, 
							 const char* pDataBuffer, unsigned short nDataSize) = 0;
	
};


class Socket
{
public:
    Socket();
    virtual ~Socket();

    // Server initialization
    bool create(IObserver *ob);
    bool bind ( const int port );
    int listen() const;
    int accept ( int fd ) const;

    // Client initialization
    bool connect ( const std::string host, const int port );

    // Data Transimission
    int send (int fd, const std::string ) const;
    int recv (int fd, std::string& ) const;
    int doRecv (int fd);
    int writen(int fd, const char* msg, int size) const;
    int readn(int fd, char* buf, int size) const;
    bool send(int fd,  unsigned short nOpcode, const char* pDataBuffer, const unsigned int& nDataSize);
    void closeFd(int fd);
    void set_non_blocking (int fd, const bool );

    bool is_valid() const { return m_sock != -1; }

    void saveDataItem(int fd);
    int parseRData(int fd);

protected:
	IObserver*         mObserver;

    clock_t tStart;  //计算程序运行时间
    int m_sock;
    sockaddr_in m_addr;

    char		m_cbSendBuf[NET_PACKET_SIZE];
    char		m_cbRecvBuf[NET_PACKET_SIZE];
    char		m_cbDataBuf[NET_PACKET_SIZE];
	int			m_nRecvSize;
};


#endif

